﻿#region Licence
// <copyright file="Core/NotificationsViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using Core.Class;
using Core.Messages;
using Database.POCO;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using Helpers.Mef;
using Interfaces.Contracts;
using Interfaces.Enums;

#endregion

namespace Core.ViewModel
{
    public class NotificationsViewModel : ViewModelBaseCore
    {
        [ImportMany(typeof(IOpenObjectModule))]
        public IEnumerable<Lazy<IOpenObjectModule, IOpenObjectModuleMetada>> OpenServices { get; set; }

        #region properties

        private List<StatutNotification> _statutsNotifications;
        public List<StatutNotification> StatutsNotifications
        {
            get { return _statutsNotifications; }
            set
            {
                _statutsNotifications = value;
                RaisePropertyChanged(() => StatutsNotifications);
            }
        }

        private StatutNotification _selectedStatutNotificationSystem;
        public StatutNotification SelectedStatutNotificationSystem
        {
            get { return _selectedStatutNotificationSystem; }
            set
            {
                _selectedStatutNotificationSystem = value;
                RaisePropertyChanged(() => SelectedStatutNotificationSystem);
                LoadNotificationSystem();
            }
        }

        private StatutNotification _selectedStatutNotification;
        public StatutNotification SelectedStatutNotification
        {
            get { return _selectedStatutNotification; }
            set
            {
                _selectedStatutNotification = value;
                RaisePropertyChanged(() => SelectedStatutNotification);
                LoadNotificationUsers();
            }
        }

        private List<ModuleNotification> _modulesNotifications;
        public List<ModuleNotification> ModulesNotifications
        {
            get { return _modulesNotifications; }
            set
            {
                _modulesNotifications = value;
                RaisePropertyChanged(() => ModulesNotifications);
            }
        }

        private ModuleNotification _selectedModuleNotification;
        public ModuleNotification SelectedModuleNotification
        {
            get { return _selectedModuleNotification; }
            set
            {
                _selectedModuleNotification = value;
                RaisePropertyChanged(() => SelectedModuleNotification);
                LoadNotificationUsers();
            }
        }

        private SysNotificationUser _selectedNotificationUser;
        public SysNotificationUser SelectedNotificationUser
        {
            get { return _selectedNotificationUser; }
            set
            {
                _selectedNotificationUser = value;
                OpenNotificationUser(value);
                RaisePropertyChanged(() => SelectedNotificationUser);
            }
        }

        private SysNotification _selectedNotification;
        public SysNotification SelectedNotification
        {
            get { return _selectedNotification; }
            set
            {
                _selectedNotification = value;
                OpenNotification(value);
                RaisePropertyChanged(() => SelectedNotification);
            }
        }
        public ObservableCollection<SysNotificationUser> NotificationUsers { get; set; }
        public ObservableCollection<SysNotification> Notifications { get; set; } 

        public RelayCommand CancelCommand { get; set; }

        #endregion

        public NotificationsViewModel()
        {
            CompositionInitializer.AddPartAndComposeContainer(this);

            CancelCommand = new RelayCommand(Cancel, CanCancel);
            LoadNotifications();
        }

        #region relaycommand

        private void OpenNotification(SysNotification obj)
        {
            if (obj != null)
            {
                obj.IsRead = true;
                DatabaseService.Service.Save<SysNotification>(obj);
                Notifications.Remove(obj);
            }
        }

        private void OpenNotificationUser(SysNotificationUser obj)
        {
            if (obj != null)
            {
                var notifType = (ValueNotificationEnum) obj.Type;
                if (notifType.HasFlag(ValueNotificationEnum.ToOpen))
                {
                    if (OpenServices != null && OpenServices.Any())
                    {
                        //On cherche le service qui correspond au module de l'item
                        var services =
                            OpenServices.Where(s => s.Metadata.Module == obj.Module);
                        if (services.Any())
                        {
                            services.First().Value.OpenObject(obj, this);
                        }
                    }
                }

                obj.IsRead = true;
                DatabaseService.Service.Save<SysNotificationUser>(obj);
                NotificationUsers.Remove(obj);
            }
        }

        private bool CanCancel()
        {
            return NavigationService.CanGoBack();
        }

        private void Cancel()
        {
            Messenger.Default.Send<RefreshNotificationMessage>(new RefreshNotificationMessage{IsRefresh = true});
            NavigationService.NavigateTo<AccueilViewModel>(new object[] { }, "RefreshDatas", new object[] { });
        }

        #endregion

        #region private

        private void LoadNotifications()
        {

            //On charge les statuts et les modules de notification
            StatutsNotifications = new List<StatutNotification>
                                   {
                                       new StatutNotification
                                       {
                                           Libelle =
                                               LocalizedService
                                               .LocalizedFromKey(
                                                   "NotificationEnumEtat_NonLues"),
                                           Statut = 0
                                       },
                                       new StatutNotification
                                       {
                                           Libelle =
                                               LocalizedService
                                               .LocalizedFromKey(
                                                   "NotificationEnumEtat_Lues"),
                                           Statut = 1
                                       },
                                       new StatutNotification
                                       {
                                           Libelle =
                                               LocalizedService
                                               .LocalizedFromKey(
                                                   "NotificationEnumEtat_Toutes"),
                                           Statut = 2
                                       }
                                   };

            ModulesNotifications = new List<ModuleNotification>
                                   {
                                       new ModuleNotification
                                       {
                                           Libelle = 
                                           LocalizedService
                                           .LocalizedFromKey(
                                                    "NotificationModule_Tous"),
                                           TypeModule = 999
                                       }
                                   };

            //Par défault - Tous les modules
            SelectedModuleNotification = ModulesNotifications.First(m => m.TypeModule == 999);

            //Par défault - Les notifications non lues
            SelectedStatutNotification= StatutsNotifications.First(s => s.Statut == 0);
            SelectedStatutNotificationSystem = StatutsNotifications.First(s => s.Statut == 0);

            LoadNotificationUsers();
            LoadNotificationSystem();
        }

        private void LoadNotificationUsers()
        {
            if (SelectedModuleNotification != null && SelectedStatutNotification != null)
            {

                List<SysNotificationUser> results;

                //Tri sur le statut
                if (SelectedStatutNotification.Statut == 2)
                {
                    results =
                        DatabaseService.Service.Where<SysNotificationUser>(
                            n => n.Utilisateur.ID == AccessControlService.CurrentUser.ID).ToList();
                }
                else
                {
                    //Indique que l'on souhaite le statut lu ou non lu
                    var statut = SelectedStatutNotification.Statut == 1;
                    results =
                        DatabaseService.Service.Where<SysNotificationUser>(
                            n => n.IsRead == statut && n.Utilisateur.ID == AccessControlService.CurrentUser.ID).ToList();
                }

                //Tri sur les modules
                var notifs = SelectedModuleNotification.TypeModule == 999
                    ? results
                    : results.Where(n => n.Module == SelectedModuleNotification.TypeModule);

                if (NotificationUsers != null)
                {
                    NotificationUsers.Clear();    
                }
                else
                {
                    NotificationUsers = new ObservableCollection<SysNotificationUser>();
                }

                foreach (var notif in notifs.OrderByDescending(n => n.SysDateCreation))
                {
                    NotificationUsers.Add(notif);
                }
            }
        }

        private void LoadNotificationSystem()
        {
            if (SelectedStatutNotificationSystem != null)
            {

                List<SysNotification> results;

                //Tri sur le statut
                if (SelectedStatutNotificationSystem.Statut == 2)
                {
                    results = DatabaseService.Service.GetAll<SysNotification>().ToList();
                }
                else
                {
                    //Indique que l'on souhaite le statut lu ou non lu
                    var statut = SelectedStatutNotificationSystem.Statut == 1;
                    results = DatabaseService.Service.Where<SysNotification>(n => n.IsRead == statut).ToList();
                }

                if (Notifications != null)
                {
                    Notifications.Clear();
                }
                else
                {
                    Notifications = new ObservableCollection<SysNotification>();
                }

                foreach (var notif in results.OrderByDescending(n => n.SysDateCreation))
                {
                    Notifications.Add(notif);
                }
            }
        }
        #endregion
    }

    public class StatutNotification
    {
        public int Statut { get; set; }
        public string Libelle { get; set; }
    }

    public class ModuleNotification
    {
        public int TypeModule { get; set; }
        public string Libelle { get; set; }
    }
}
